<?php

namespace Models;

use Models\BaseModel;
use Observers\CommentObserver;

class Comment extends BaseModel
{
    /**
     * 表名
     * @var string
     */
    protected $table = 'comment';

    /**
     * 默认连接
     * @var string
     */
    protected $connection = 'default';

    /**
     * 主键ID字段
     * @var string
     */
    protected $primaryKey = 'comm_ID';

    /**
     * 是否维护时间戳
     * @var bool
     */
    public $timestamps = false;

    /**
     * 可以被批量赋值的属性。
     * @var array
     */
    protected $fillable = [
        'comm_LogID',
        'comm_IsChecking',
        'comm_RootID',
        'comm_ParentID',
        'comm_AuthorID',
        'comm_Name',
        'comm_Email',
        'comm_HomePage',
        'comm_Content',
        'comm_PostTime',
        'comm_IP',
        'comm_Agent',
        'comm_Meta',
    ];

    public static function boot()
    {
        parent::boot();
        static::observe(new CommentObserver());
    }

    /**
     * 获取comm_Meta
     *
     * @param string $value
     * @return array
     */
    public function getCommMetaAttribute($value): array
    {
        return empty($value) ? [] : unserialize($value);
    }

    /**
     * 设置comm_Meta
     *
     * @param string $value
     * @return string
     */
    public function setCommMetaAttribute($value): string
    {
        return $this->attributes['comm_Meta'] = empty($value) ? '' : serialize($value);
    }

    /**
     * 关联用户
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function member(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(new Member(), 'mem_ID', 'comm_AuthorID');
    }

    /**
     * 关联文章
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function post(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(new Post(), 'log_ID', 'comm_LogID');
    }

    /**
     * 上级评论
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function commentParent(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(new Comment(), 'comm_ID', 'comm_ParentID');
    }

    /**
     * 顶级评论
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function commentRoot(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(new Comment(), 'comm_ID', 'comm_RootID');
    }
}
